import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { PluginLocal, PluginLocalTool } from '@shared/types/entity'
export type PluginLocalItem = PluginLocal & {
  tools: PluginLocalTool[]
}

interface PluginLocalStore {
  data: PluginLocal[]
  initData: () => Promise<void>
  drater: {
    type: 'plugin' | 'tool'
    open: boolean
  }
  setDrater: (type: 'plugin' | 'tool', open: boolean) => void
  form: {
    type: 'add' | 'edit'
    data?: PluginLocal
  }
  editForm: (type: 'add' | 'edit', data?: PluginLocal) => void
}

const usePluginLocalStore = create<PluginLocalStore>()(
  immer(
    (set): PluginLocalStore => ({
      data: [],
      initData: async () => {
        const data = await window.api.pluginLocal.getList({})
        set((state) => {
          state.data = data
        })
      },
      drater: {
        type: 'plugin',
        open: false
      },
      setDrater: (type, open) =>
        set((state) => {
          state.drater.type = type
          state.drater.open = open
        }),
      form: { type: 'add' },
      editForm: (type, data?) =>
        set((state) => {
          state.form.type = type
          state.form.data = data || {
            mark: '',
            name: ''
          }
        })
    })
  )
)

export default usePluginLocalStore
